/*
 * @Author: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @Date: 2025-06-30 16:12:29
 * @LastEditors: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @LastEditTime: 2025-09-02 12:57:17
 * @FilePath: /server/workspace/src/base/scheduler.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */


 #pragma  once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <functional>
#include <sys/ucontext.h>
#include <ucontext.h>
#include "mutex.h"
namespace Yizhi{
    

    class Fiber:public std::enable_shared_from_this<Fiber>{

        public:
        enum State{
        INIT=0,
        READY,
        EXEC,
        HOLD,
        TERM,
        EXECPT
    };
        public:
        typedef std::shared_ptr<Fiber> ptr;
        typedef Mutex MutexType;

        public:
        ///@brief 任务协程构造
        Fiber(std::function<void()> cb,bool user_caller=false,size_t stacksize=0);
        
        ~Fiber();

        ///@brief 切入协程执行
        void resunme();

        ///@brief
        void yield();

        ///@brief 重置任务函数及当前协程状态，复用栈空间
        void reset(std::function<void()> cb);
        
       void call();
       
       void back();

        bool IsTERM(){
            return m_state==TERM;
        }
        bool IsREADY(){
            return m_state==READY;
        }
        bool IsEXEC(){
            return m_state==EXEC;
        }
        bool IsINIT(){
            return m_state==INIT;
        }
        bool IsEXCEPT(){
            return m_state==EXECPT;
        }
        bool IsHOLD(){
            return m_state==HOLD;
        }
        
        void setState(State state){
            m_state=state;
        }
        
        public:


        ///@brief 执行入口
        static void MainFunc();

        ///@brief 调度线程的协程执行入口
        static void CallMainFUnc();

        ///@brief 协程行使权转让，当前携程切入后台，并且状态为ready
        static void YieldToReady();

        ///@brief 协程行使权转让,后台挂起，状态为hold
        static void YieldToHold();
        
        ///@brief 协程总数
        static uint64_t TotalFibers();
        
        ///@brief 获取当前主携程
        static Fiber::ptr GetThis();

        ///@brief 设置当前主携程
        static void SetThis(Fiber *f);

        static uint64_t GetFiberId();

        private:
        ///@brief 主协程构造
        Fiber();

        private:

        ///@brief 自身状态
        State m_state=INIT;

        ///@brief 上下文
        ucontext_t m_ctxt;

        // ///@brief 互斥量
        // MutexType m_mutex;

        ///@brief 任务函数
        std::function<void()> m_cb;

        ///@brief 栈大小
        size_t m_stacksize=0;
        
        ///@brief 栈指针
        void *m_stack=nullptr;

        ///@brief 
        uint64_t m_id=0;
    };

}